var AnnouceAPI = (function($) {
	var pullArr = [{start:0,pulling:false},{start:0,pulling:false},{start:0,pulling:false},{start:0,pulling:false}]
	var pull0,pull1,pull2,pull3;
	var limit = 12;
	var readflag = '';
	var user;
	
	$.init();
	$.plusReady(function() {
		baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}

	function baseSetup() {
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		user = app.getState();
		if (user.APPMenu.WorkNotice) {
			mui('#create')[0].removeAttribute('style')
		}
		mui('#slider').slider().stopped = true; //禁止左右滑动
		bindUpFreshOnScroll() //绑定上拉加载事件
		
		// 获取活动页签 进行首次数据请求
		// var activeTab = $('#sliderIndicator .mui-indicator.mui-active')[0];
		// var tabIndex = activeTab.getAttribute('data-index')
		// requestData(tabIndex);
		requestData(0);
		requestData(1);
		requestData(2);
		requestData(3);
		
		// 监听左右滑动切换顶部tab页签
		// var slider = document.getElementById('slider');
		// slider.addEventListener('slide', function(event) {
		// 	var index = event.detail.slideNumber;
		// 	$('#sliderIndicator .mui-indicator[data-index="' + index + '"]')[0].classList.add('mui-active');
		// });
		// 监听点击切换顶部tab页签
		var indicators = document.querySelectorAll('#sliderIndicator .mui-indicator');
		for (var i = 0; i < indicators.length; i++) {
			indicators[i].addEventListener('tap', function() {
				var oldActive = $('#sliderIndicator .mui-indicator.mui-active')[0];
				if (oldActive) {
					if (oldActive == this) {
						return
					}
					oldActive.classList.remove('mui-active')
				}
				var newIndex = parseInt(this.getAttribute('data-index'))
				this.classList.add('mui-active')
				mui('#slider').slider().gotoItem(newIndex, 100)
			});
		}
		
		// 创建新的公告
		mui('body').on('tap','#create',openEditPage) 
	}
	
	function openEditPage(){
		var url = 'announceEdit.html';
		var webviewId = 'announceEdit.html';
		webview = plus.webview.create(url, webviewId, {
			titleNView: {
				backgroundColor: '#fff',
				titleText: '发布公告',
				titleColor: '#1D2334',
				autoBackButton: true,
			}
		},{});
		webview.show()
		webview.addEventListener('close',function(){
			refreshMainPage(0);
			refreshMainPage(1);
			refreshMainPage(2);
			refreshMainPage(3);
		})
	}
	
	function openDetailPage(){
		var classStr = this.getAttribute('class')
		if (classStr.indexOf('deleteBtn') != -1) {
			return
		}
		var rowid = this.getAttribute('row');
		var flag = this.getAttribute('data-flag');
		if (!rowid) {
			console.log("没有获取到rowid");
			return
		}
		if (this.getAttribute('status') == 'N') { //已保存
			var url = 'announceEdit.html';
			var webviewId = 'announceEdit.html';
			webview = plus.webview.create(url, webviewId, {
				titleNView: {
					backgroundColor: '#fff',
					titleText: '发布公告',
					titleColor: '#1D2334',
					autoBackButton: true,
				}
			},{row: rowid});
			webview.show()
			webview.addEventListener('close',function(){
				refreshMainPage(0);
				refreshMainPage(1);
				refreshMainPage(2);
				refreshMainPage(3);
			})
			return 
		}
		var url = 'announceDetail.html';
		var webviewId = 'announceDetail.html';
		webview = plus.webview.create(url, webviewId, {
			titleNView: {
				backgroundColor: '#fff',
				titleText: '通知详情',
				titleColor: '#1D2334',
				autoBackButton: true,
			}
		},{row: rowid,flag: flag});
		webview.show('slide-in-right')
		webview.addEventListener('close',function(){
			refreshMainPage(0);
			refreshMainPage(1);
			refreshMainPage(2);
			refreshMainPage(3);
		})
	}
	
	function bindUpFreshOnScroll(){
		pull0 = $('#scroll0').pullToRefresh({
			up: {
				callback: function() {
					requestData(0)
				}
			}
		});
		pull1 = $('#scroll1').pullToRefresh({
			up: {
				callback: function() {
					requestData(1)
				}
			}
		});
		pull2 = $('#scroll2').pullToRefresh({
			up: {
				callback: function() {
					requestData(2)
				}
			}
		});
		pull3 = $('#scroll3').pullToRefresh({
			up: {
				callback: function() {
					requestData(3)
				}
			}
		});
		pullArr[0].pullObj = pull0;
		pullArr[1].pullObj = pull1;
		pullArr[2].pullObj = pull2;
		pullArr[3].pullObj = pull3;
	}
	
	function requestData(index){
		// console.log(index)
		// console.log(JSON.stringify(pullArr[index]));
		if(!pullArr[index]){
			console.log('错误')
			return
		}
		if (pullArr[index].pulling && pullArr[index].pullObj) {
			pullArr[index].pulling = false //结束刷新
			pullArr[index].pullObj.endPullUpToRefresh()
			return;
		}
		pullArr[index].pulling = true //开始刷新了
	
		/* 传1未读/传2已读 */
		readflag = '1'; // 1 未读
		var method = 'web.INMPlatform:FindWorkNoticeByUser';
		if(index == '1'){
			readflag = '2';  // 2 已读
		}else if(index == '2'){
			readflag = 'Y';  // Y 已发送
			method = 'web.INMPlatform:FindWorkNotice'
		}else if(index == '3'){
			readflag = 'N';  // N 已保存
			method = 'web.INMPlatform:FindWorkNotice'
		}
		var arg = {
			parr: readflag,
			input: '',
			APPLoginID: user.loginID,
			APPPerID: user.loginPerID,
			loginID: user.loginID,
			start: pullArr[index].start,
			limit: limit
		}
		var paramDict = {
			'method': method,
			'params': JSON.stringify(arg),
			'type': 'RecQuery'
		}
		// console.log(JSON.stringify(arg));
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			var dataArr = result['data'];
			updateAnnounceList(dataArr,index)
		}, function(errorStr) {
			mui.toast(errorStr)
			pullArr[index].pulling = false;
			pullArr[index].pullObj.endPullUpToRefresh()
		});
	}
	
	// 渲染数据
	function updateAnnounceList(dataArr,index){
		if(index == 0){
			// 显示未读数目
			$('#unreadConunt')[0].innerHTML = '(' + dataArr.length +')';
		}
		
		var scroll = document.getElementById('scroll' + index);
		var ul = scroll.querySelector('ul');
		if(pullArr[index].start == 0 ){
			// 这里就不再重复显示‘没有更多数据了’
			if (dataArr.length == 0) {
				pullArr[index].pullObj.options.up.contentnomore = ''
				showNullTip(index,'暂时没有内容，去其他地方看看吧！')
			}else{
				hideNullTip(index)
			}
			ul.innerHTML = '';
		}
		var TomcatUrl = user.TomcatUrl||""
		for (var i=0;i<dataArr.length;i++) {
			var one = dataArr[i];
			var readStatus = one.readStatus;
			var NoticeLevelDesc = one.NoticeLevelDesc
			var src = 'http://iph.href.lu/400x300?text='+NoticeLevelDesc;
			var level = 'normal'
			if(NoticeLevelDesc == '重要消息'){
				level ='imp'
			}else if(NoticeLevelDesc == '非常重要'){
				level ='very'
			}else if(NoticeLevelDesc == '紧急消息'){
				level ='jinji'
			}
			var NoticeFileUrl = one.NoticeFileUrl||""
			var fileStr = ''
			if (NoticeFileUrl != '') {
				fileStr = '<div class="file nurfont nur-target"></div>'
				//取第一张图片作为配图
				if (TomcatUrl !="") {
					var filearr = NoticeFileUrl.split(',')
					for (var j = 0; j < filearr.length; j++) {
						var url = filearr[j]
						url = url.toLowerCase()
						if (url.endsWith(".png")||url.endsWith(".jpg")||url.endsWith(".jpeg")||url.endsWith(".gif")||url.endsWith(".bmp")) {
							src = TomcatUrl + '/'+filearr[j]
							break
						}
						
					}
				}
				
			}
			var levelStyle = ''
			var color = one.NoticeLevelColor
			if (color && color != "") {
				levelStyle = 'style="color:'+color+';border-color:'+color+';"'
			}
			var html = 'msgBody" status="'+one.NoticeStatus+'" row="'+ one.rw +'" data-flag="' + readStatus + '">'+
					'<img class="mui-media-object mui-pull-left" src="'+ src +'">'+
					'<div class="mui-media-body">'+ one.NoticeTitle +'<p class="mui-ellipsis-2">'+ one.NoticeDate +'</p></div>'+
					'<div class="right"><div class="time">'+one.NoticeTime+'</div>'+fileStr+
						'<div class="level" "'+level+'" '+levelStyle+'>'+NoticeLevelDesc+'</div>'+
					'</div></div>'
			if (index == 3) { //只有已保存有删除功能 发布了就不能删除和撤回了
				html = '<div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-red deleteBtn">删除</a></div>'+
					'<div class="mui-slider-handle '+html;
			}else{
				html = '<div class="'+html;
			}
			var liDom = document.createElement('li')
			ul.appendChild(liDom)
			liDom.setAttribute('class','mui-table-view-cell mui-media')
			liDom.innerHTML = html
			liDom.querySelector('.msgBody').addEventListener('tap',openDetailPage)
			if (index == 3) {
				liDom.querySelector('.deleteBtn').addEventListener('tap',deleteBtnTapped)
			}
		}
		pullArr[index].pulling = false;
		pullArr[index].start += dataArr.length;
		if(dataArr.length >= limit){
			pullArr[index].pullObj.endPullUpToRefresh()
		}else{
			pullArr[index].pullObj.endPullUpToRefresh(true)
		}
	}
	function deleteBtnTapped(){
		var li = this.parentNode.parentNode
		var rowid = li.querySelector('.msgBody').getAttribute('row');
		mui.confirm('确认删除吗？', '删除提醒', ['取消','删除'], function(e) {
			if (e.index == 1) {
				deleteAction(2,li)
			} else {
				setTimeout(function() {
					$.swipeoutClose(li);
				}, 0);
			}
		});
	}
	
	function deleteAction(rw,li){
		var arg = {
			rw:rw,
			loginID: user.loginID
		}
		var paramDict = {
			'method': 'web.INMPlatform:DelWorkNotice',
			'params': JSON.stringify(arg),
			'type': 'Method'
		}
		// console.log(JSON.stringify(arg));
		plus.nativeUI.showWaiting('正在删除...', {modal: false})
		$.DHCWebService(paramDict, function(result) {
			plus.nativeUI.closeWaiting();
			//console.log(JSON.stringify(result))
			if (result.msg == '1') { //删除成功
				refreshMainPage(3)
			}else{
				$.swipeoutClose(li);
				mui.toast(result.msg)
			}
		}, function(errorStr) {
			plus.nativeUI.closeWaiting();
		});
	}
	function showNullTip(index,msg){
		mui('.nullData')[index].style.display = 'block';
		mui('.nullTip')[index].innerHTML = msg
	}
	
	function hideNullTip(index){
		// console.log(index)
		mui('.nullData')[index].style.display = 'none';
	}
	
	// 
	function refreshMainPage(index) {
		pullArr[index].start = 0;
		pullArr[index].pullObj.endPullUpToRefresh(true);
		$('#wrapper' + index).scroll().scrollTo(0,0,100);
		$('#wrapper' + index + ' ul')[0].innerHTML = ''
		pullArr[index].pullObj.refresh(true);
		mui('#scroll'+index +'.msgBody').each(function (index,element) {
			element.removeEventListener('tap',openDetailPage)
		})
		mui('#scroll'+index +'.deleteBtn').each(function (index,element) {
			element.removeEventListener('tap',deleteBtnTapped)
		})
		requestData(index)
	}
	
	var AnnouceAPI = {};
	AnnouceAPI.outRefresh = refreshMainPage; // 让外部接口等于内部接口 直接接受入参
	return AnnouceAPI
})(mui);

function refreshData(index){
	// console.log(index)
	AnnouceAPI.outRefresh(index) // true表示重置页面数据，从第0页开始查起
}